﻿(function () {
    "use strict";

    /*DEBUG VARS*/
    var DEBUG = false;

    //resource variables
    var recentPostsTitle = WinJS.Resources.getString('recentPostsTitle').value;
    var categoryTitle = WinJS.Resources.getString('categoryTitle').value;
    var offlineTitle = WinJS.Resources.getString('offlineTitle').value;
    var aboutTitle = WinJS.Resources.getString('aboutTitle').value;
    var sharingErrorMessage = WinJS.Resources.getString('shareErrorMessage').value;

    //Ad Variables
    var applicationId = WinJS.Resources.getString('applicationId').value;
    var adUnitId = WinJS.Resources.getString('adUnitId').value;

    var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();

    var appView = Windows.UI.ViewManagement.ApplicationView;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;

    var _element;
    var recentList = [];
    var offlineList = [];
    var categoryList = [];
    var aboutList = [];
    var unifiedList;
    var groupedList;

    var promise = null;
    var _first = true;
    var _saveAdsForRemoval = null;

    //override tap behaviour
    //save toggle pressed
    var origFunc = WinJS.UI._SelectionMode.prototype.togglePressed;

    var utilities = WinJS.Utilities,
        Key = utilities.Key,
        Promise = WinJS.Promise,
        Signal = WinJS._Signal,
        Animation = WinJS.UI.Animation,
        AnimationHelper = WinJS.UI._ListViewAnimationHelper;

    function log(str) {
        
        if (DEBUG && console && console.log) {
            console.log(str);
        }
    };

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // Navigates to the groupHeaderPage. Called from the groupHeaders,
        // keyboard shortcut and iteminvoked.
        navigateToGroup: function (key) {
            WinJS.Navigation.navigate("/pages/groupDetail/groupDetail.html", { groupKey: key });
        },

        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            _saveAdsForRemoval = [];
            _element = element


            //set progress ring
            var parent = element.querySelector('section');
            var pHeight = (parent.offsetHeight / 2) - parent.offsetTop;
            var ringContainer = element.querySelector('.progress-container');
            var rHeight = ringContainer.offsetHeight;
            var marginTop = pHeight + (rHeight / 2);
            ringContainer.style.marginTop = marginTop + "px";

            //clear listview
            var lw = _element.querySelector("#zoomedInListView");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyRecentList");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyOfflineList");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyCategoryList");
            lw.winControl.itemDataSource = null;


            //Share fail dialog
            dataTransferManager.addEventListener("datarequested", dataRequested);

            var that = this;

            toggleLoading(true, null);

            promise = Data.unifyItemsForListLayout().then(function (list) {
                unifiedList = list;
                groupedList = Data.getGroupedList(list);
                that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
            });
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.

            if (promise != null) {
                promise.cancel();
            }
            for (var i = 0; i < _saveAdsForRemoval.length; i++) {
                _saveAdsForRemoval[i].dispose(true);
            }
            _saveAdsForRemoval = null;
            dataTransferManager.removeEventListener("datarequested", dataRequested);
        },

        // This function updates the page layout in response to viewState changes.
        updateLayout: function (element, viewState, lastViewState) {
            if (promise != null) {
                promise.cancel();
            }
            _element = element;

            //clear listview
            var lw = _element.querySelector("#zoomedInListView");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyRecentList");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyOfflineList");
            lw.winControl.itemDataSource = null;

            var lw = _element.querySelector("#snappyCategoryList");
            lw.winControl.itemDataSource = null;

            /// <param name="element" domElement="true" />
            //var listView = element.querySelector("#zoomedInListView").winControl;
            if (lastViewState !== viewState) {
                if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
                  
                    if (typeof unifiedList === "undefined") {
                        var that = this;

                        toggleLoading(true, null);

                        promise = Data.unifyItemsForListLayout().then(function (list) {
                            unifiedList = list;
                            groupedList = Data.getGroupedList(list);
                            that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
                        });
                    } else {
                        this._initializeLayout(viewState, element);
                    }
                } else {
                    this._initializeLayout(viewState, element);
                }
            } else {
                if (typeof groupedList === "undefined") {
                    var that = this;

                    toggleLoading(true, null);

                    promise = Data.unifyItemsForListLayout().then(function (list) {
                        unifiedList = list;
                        groupedList = Data.getGroupedList(list);
                        that._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element);
                    });
                } else {
                    this._initializeLayout(viewState, element);
                }
            }
        },

        // This function updates the ListView with new layouts
        _initializeLayout: function (viewState, element) {

            //check if app is in snapp-state
            if (viewState === appViewState.snapped) {
                //list layout

                //clear list - otherwise the post will be twice in the list
                recentList = [];
                offlineList = [];
                categoryList = [];
                aboutList = [];

                //for sorting the list & removing ad
                for (var i = 0; i < unifiedList.length; i++) {
                    if (unifiedList[i].title == recentPostsTitle || unifiedList[i].key == recentPostsTitle) {
                        if (unifiedList[i].ad !== true) {
                            recentList.push(unifiedList[i]);
                        }
                    } else if (unifiedList[i].title == offlineTitle || unifiedList[i].key == offlineTitle) {
                        if (unifiedList[i].ad !== true) {
                            offlineList.push(unifiedList[i]);
                        }
                    } else if (unifiedList[i].title == categoryTitle || unifiedList[i].key == categoryTitle) {
                        categoryList.push(unifiedList[i]);
                    } else if (unifiedList[i].title == aboutTitle || unifiedList[i].key == aboutTitle) {
                        aboutList.push(unifiedList[i]);
                    }
                }

                //--------------recent------------------
                if (recentList.length > 0) {
                    //show list
                    var title = element.querySelector("#recentTitle");
                    title.innerText = recentPostsTitle;
                    title.addEventListener('click', navigateFromHeader, false);
                    //calculate heights
                    var titleHeight = title.offsetHeight;
                    var listHeight = recentList.length * 103;
                    var containerHeight = titleHeight + listHeight;
                    //set heights
                    element.querySelector("#recentListContainer").style.height = listHeight + "px";
                    element.querySelector("#recentContainer").style.height = containerHeight + "px";
                    //set list bindings
                    var bindingList = new WinJS.Binding.List(recentList);
                    var listView = element.querySelector("#snappyRecentList").winControl;
                    listView.oniteminvoked = itemInvokedRecent;
                    listView.selectionMode = 'none';
                    listView.itemDataSource = bindingList.dataSource;
                    listView.itemTemplate = itemTemplateFunctionSnapped;
                } else {
                    //hide container
                    element.querySelector("#recentContainer").style.display = "none";
                }
                //--------------offline-----------------
                if (offlineList.length > 0) {
                    //show list
                    var title = element.querySelector("#offlineTitle");
                    title.innerText = offlineTitle;
                    title.addEventListener('click', navigateFromHeader, false);

                    //calculate heights
                    var titleHeight = title.offsetHeight;
                    var listHeight = offlineList.length * 103;
                    var containerHeight = titleHeight + listHeight;
                    //set heights
                    element.querySelector("#offlineListContainer").style.height = listHeight + "px";
                    element.querySelector("#offlineContainer").style.height = containerHeight + "px";
                    //set list bindings
                    var bindingList = new WinJS.Binding.List(offlineList);
                    var listView = element.querySelector("#snappyOfflineList").winControl;
                    listView.oniteminvoked = itemInvokedOffline;
                    listView.selectionMode = 'none';
                    listView.itemDataSource = bindingList.dataSource;
                    listView.itemTemplate = itemTemplateFunctionSnapped;
                } else {
                    //hide container
                    element.querySelector("#offlineContainer").style.display = "none";
                }
                //--------------category----------------
                if (categoryList.length > 0) {
                    //show list

                    var title = element.querySelector("#categoryTitle");
                    title.innerText = categoryTitle;
                    title.addEventListener('click', navigateFromHeader, false);

                    //calculate heights
                    var titleHeight = title.offsetHeight;
                    var listHeight = categoryList.length * 50;
                    var containerHeight = titleHeight + listHeight;
                    //set heights
                    element.querySelector("#categoryListContainer").style.height = listHeight + "px";
                    element.querySelector("#categoryContainer").style.height = containerHeight + "px";
                    //set list bindings
                    var bindingList = new WinJS.Binding.List(categoryList);
                    var listView = element.querySelector("#snappyCategoryList").winControl;
                    listView.oniteminvoked = itemInvokedCategory;
                    listView.selectionMode = 'none';
                    listView.itemDataSource = bindingList.dataSource;
                    listView.itemTemplate = itemTemplateFunctionSnapped;
                } else {
                    //hide container
                    element.querySelector("#categoryContainer").style.display = "none";
                }
                //--------------about-------------------
                
                var title = element.querySelector("#aboutTitle");
                title.innerText = aboutTitle;
                //calculate heights
                var titleHeight = title.offsetHeight;
                
                toggleLoading(false, true);
            } else {
                //grid layout

                var zoomedInListView = element.querySelector('#zoomedInListView').winControl;
                var gridLayoutOptions = {
                    groupHeaderPosition: 'top',
                    groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                };

                WinJS.UI.setOptions(zoomedInListView, {
                    itemDataSource: groupedList.dataSource,
                    groupDataSource: groupedList.groups.dataSource,
                    itemTemplate: itemTemplateFunction,
                    groupHeaderTemplate: groupHeaderTemplateFunction,
                    selectionMode: 'none',
                    oniteminvoked: itemInvoked,
                    layout: new WinJS.UI.GridLayout(gridLayoutOptions)
                });

                var zoomedOutListView = element.querySelector('#zoomedOutListView').winControl;

                WinJS.UI.setOptions(zoomedOutListView, {
                    itemDataSource: groupedList.groups.dataSource,
                    itemTemplate: myZoomedOutTemplateFunction,
                    selectionMode: 'none',
                    layout: new WinJS.UI.GridLayout()
                });
                toggleLoading(false, false);
            }
        },

        getAnimationElements: function () {
            return [[this.element.querySelector("header")], [this.element.querySelector("section")]];
        }

    });

    function toggleLoading(isLoading, isSnapped) {
        if (isLoading) {
            _element.querySelector(".progress-container").style.display = "block";
            _element.querySelector('#snappContainer').style.display = "none";;
            _element.querySelector('#fullContainer').style.display = "none";;
        }
        else {
            _element.querySelector(".progress-container").style.display = "none";
            if (isSnapped) {
                _element.querySelector('#snappContainer').style.display = "block";;
                _element.querySelector('#fullContainer').style.display = "none";;
            }
            else {
                _element.querySelector('#snappContainer').style.display = "none";;
                _element.querySelector('#fullContainer').style.display = "block";;
            }
        }
    }

    function headerButtonCallback(e) {
        log("click! " + e.firstElementChild.textContent);
        var headerTitle = e.firstElementChild.textContent;
        if (headerTitle !== aboutTitle) {
            WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                from: 'headerButton',
                headerTitle: headerTitle
            });
        }
    }

    function navigateFromHeader(e) {
        var headerTitle = e.srcElement.innerText;
        WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
            from: 'headerButton',
            headerTitle: headerTitle
        });
    }

    function getRecentDatasource(e) {
        var list = new WinJS.Binding.List()
        for (var i = 0; i < recentList.length; i++) {
            list.push(recentList[i]);
        }
        return list.dataSource;
    }

    function dataRequested(e) {
        var request = e.request;
        if (sharingErrorMessage) {
            request.failWithDisplayText(sharingErrorMessage);
        } else {
            request.failWithDisplayText("Derzeit sind keine Inhalte zum Teilen vorhanden.");
        };
    }

    function itemInvokedRecent(e) {
        var invokedItem = recentList[e.detail.itemIndex];
        if (typeof invokedItem.ad !== "undefined") {
            if (invokedItem.ad == true) {
                return null;
            }
        }
        if (invokedItem.key === recentPostsTitle) {
            if (typeof invokedItem.link !== "undefined") {
                WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                    from: 'headerButton',
                    headerTitle: recentPostsTitle
                });
            } else {
                //invoked a recentPost item
                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
            }
            
        }
    }

    function itemInvokedOffline(e) {
        var invokedItem = offlineList[e.detail.itemIndex];
        if (typeof invokedItem.ad !== "undefined") {
            if (invokedItem.ad == true) {
                return null;
            }
        }
        if (invokedItem.key === offlineTitle) {
            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
        }
    }

    function itemInvokedCategory(e) {
        var invokedItem = categoryList[e.detail.itemIndex];
        if (typeof invokedItem.ad !== "undefined") {
            if (invokedItem.ad == true) {
                return null;
            }
        }
        if (invokedItem.key === categoryTitle) {
            //invoked a category item
            WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                from: 'categoryItem',
                item: invokedItem
            });
        }
    }

    function itemInvoked(e) {
        log("invoked" + groupedList.getAt(e.detail.itemIndex).key);
        var invokedItem = groupedList.getAt(e.detail.itemIndex);

        if (typeof invokedItem.ad !== "undefined") {
            if (invokedItem.ad == true) {
                return null;
            }
        }
        if (invokedItem.key === recentPostsTitle) {
            //invoked a recentPost item
            if (typeof invokedItem.link !== "undefined") {
                WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                    from: 'headerButton',
                    headerTitle: recentPostsTitle
                });
            } else {
                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
            }
            
        } else if (invokedItem.key === categoryTitle) {
            //invoked a category item
            WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                from: 'categoryItem',
                item: invokedItem
            });
        } else if (invokedItem.key === offlineTitle) {
            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: invokedItem });
        }
    }

    //Template Function
    function itemTemplateFunctionSnapped(itemPromise) {
        return itemPromise.then(function (item) {

            var itemTemplate = _element.querySelector('#snapItem-image');

            if (item.data.isheader == true) {
                itemTemplate = _element.querySelector('#snapHeader');
            } else if (item.data.key == recentPostsTitle) {
                //if (typeof item.data.ad === "undefined") {
                if (typeof item.data.link !== "undefined") {
                    itemTemplate = _element.querySelector('#snapItem-Link');
                } else {
                    if (typeof item.data.teaserImage !== "undefined") {
                        itemTemplate = _element.querySelector('#snapItem-image');
                    } else {
                        itemTemplate = _element.querySelector('#snapItem');
                    }
                }
                
                
            } else if (item.data.key === offlineTitle) {
                //if (typeof item.data.ad === "undefined") {
                if (typeof item.data.teaserImage !== "undefined") {
                    itemTemplate = _element.querySelector('#snapItem-image');
                } else {
                    itemTemplate = _element.querySelector('#snapItem');
                }
                
            } else {
                itemTemplate = _element.querySelector('#snapItem-category');
            }

            // Render selected template to DIV container
            var container = document.createElement("div");
            itemTemplate.winControl.render(item.data, container);

            return container;
        });
    }

    //Template Function
    function itemTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {
            if (item.data == null) {
                return _element.querySelector('#itemTemplate-RecentPost');
            }
            // Select template
            var itemTemplate;
            if (item.data.key === recentPostsTitle) {
                if (typeof item.data.ad !== "undefined") {
                    var adDiv = document.createElement("div");
                    adDiv.style.height = "250px";
                    adDiv.style.width = "250px";
                    var myAdControl = new MicrosoftNSJS.Advertising.AdControl(adDiv,
                                    {
                                        applicationId: applicationId,
                                        adUnitId: adUnitId
                                    });
                    _saveAdsForRemoval.push(myAdControl);
                    return adDiv;

                } else {
                    if (typeof item.data.link !== "undefined") {
                        itemTemplate = _element.querySelector('#itemTemplate-Link');
                    }else if (item.index === 0) {
                        if (typeof item.data.teaserImage !== "undefined") {
                            itemTemplate = _element.querySelector('#itemTemplate-RecentPost-First-Image');
                        } else {
                            itemTemplate = _element.querySelector('#itemTemplate-RecentPost-First');
                        }
                    } else {
                        if (typeof item.data.teaserImage !== "undefined") {
                            itemTemplate = _element.querySelector('#itemTemplate-Image');
                        } else {
                            itemTemplate = _element.querySelector('#itemTemplate-RecentPost');
                        }
                    }
                }
            } else if (item.data.key === categoryTitle) {

                itemTemplate = _element.querySelector('#itemTemplate-Category');

            } else if (item.data.key === offlineTitle) {
                if (typeof item.data.ad !== "undefined") {
                    //itemTemplate = _element.querySelector('#itemTemplate-Advertising');
                    var adDiv = document.createElement("div");
                    adDiv.style.height = "250px";
                    adDiv.style.width = "250px";
                    var myAdControl = new MicrosoftNSJS.Advertising.AdControl(adDiv,
                                    {
                                        applicationId: applicationId,
                                        adUnitId: adUnitId
                                    });
                    return adDiv;
                } else {
                    if (typeof item.data.teaserImage !== "undefined") {
                        
                        itemTemplate = _element.querySelector('#itemTemplate-Image');
                    } else {
                        itemTemplate = _element.querySelector('#itemTemplate-RecentPost');
                    }
                }
            } else if (item.data.key === aboutTitle) {
                if (item.data.class === "team") {
                    itemTemplate = _element.querySelector('#itemTemplate-About-Team-' + item.data.teamkey);

                } else {
                    itemTemplate = _element.querySelector('#itemTemplate-About');
                }
            }

            // Render selected template to DIV container
            var container = document.createElement("div");
            itemTemplate.winControl.render(item.data, container);

            return container;
        });
    }

    function groupHeaderTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {
            var groupHeaderTemplate;
            if (item.data.title === aboutTitle) {
                groupHeaderTemplate = _element.querySelector('#groupHeaderTemplate-About');

            } else {
                groupHeaderTemplate = _element.querySelector('#groupHeaderTemplate');
            }

            // Render selected template to DIV container

            var container = document.createElement("div");
            groupHeaderTemplate.winControl.render(item.data, container);
            return container;
        });
    }

    function myZoomedOutTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {
            var MyZoomedOutTemplate = _element.querySelector('#MyZoomedOutTemplate');

            // Render selected template to DIV container
            var container = document.createElement("div");
            MyZoomedOutTemplate.winControl.render(item.data, container);
            return container;
        });
    }

    //override toggle pressed
    WinJS.UI._SelectionMode.prototype.togglePressed = function SelectionMode_togglePressed(add) {
        if (!this.staticMode()) {
            // If we are adding the pressed effect do it immediately because we
            // already delayed it but if we are removing it add the delay here.
            if (add) {

                if (typeof this.pressedItem.children[0].children[0] !== "undefined") {
                    if (this.pressedItem.children[0].children[0].className == "about-small" || this.pressedItem.children[0].children[0].className == "about-big") {
                        return;
                    }
                } else if (typeof this.pressedItem.children[1] !== "undefined" && typeof this.pressedItem.children[1].children[0] !== "undefined") {
                    if (this.pressedItem.children[1].children[0].className == "about-small" || this.pressedItem.children[1].children[0].className == "about-big") {
                        return;
                    }
                }

                msWriteProfilerMark("WinJS.UI.ListView:applyPressedUI,info");
                utilities.addClass(this.pressedItem, WinJS.UI._pressedClass);

                // Shrink by 97.5% unless that is larger than 7px in either direction. In that case we cap the 
                // scale so that it is no larger than 7px in either direction. We keep the scale uniform in both x
                // and y directions. Note that this scale cap only works if getItemPosition returns synchronously
                // which it does for the built in layouts.
                var scale = 0.975;
                var maxPixelsToShrink = 7;
                this.site._layout.getItemPosition(this.pressedIndex).then(function (pos) {
                    if (pos.contentWidth > 0) {
                        scale = Math.max(scale, (1 - (maxPixelsToShrink / pos.contentWidth)));
                    }
                    if (pos.contentHeight > 0) {
                        scale = Math.max(scale, (1 - (maxPixelsToShrink / pos.contentHeight)));
                    }
                }, function () {
                    // Swallow errors in case data source changes
                });

                this.pressedItem.style.transform = "scale(" + scale + "," + scale + ")";

            } else {
                var element = this.pressedItem;
                setImmediate(function () {
                    if (utilities.hasClass(element, WinJS.UI._pressedClass)) {
                        msWriteProfilerMark("WinJS.UI.ListView:removePressedUI,info");
                        utilities.removeClass(element, WinJS.UI._pressedClass);
                        Animation.pointerUp(element);
                    }
                });
            }
        }
    }

    WinJS.Namespace.define('MyFunctions', {
        headerButtonCallback: headerButtonCallback,
        getRecentDatasource: getRecentDatasource
    });

})();

